// 获取库存列表（带分页和筛选）
const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;
const collection = db.collection("inStock");

// 获取入库记录列表
exports.getInStockRecords = async (page = 1, pageSize = 10, filters = {}) => {
	try {
		// 处理过滤条件
		let enhancedFilter = {
			isDel: 0,
		}; // 基础过滤条件

		// 移除 filters 中的空值、undefined 和 null
		Object.keys(filters).forEach((key) => {
			if (
				filters[key] !== undefined &&
				filters[key] !== null &&
				filters[key] !== ""
			) {
				enhancedFilter[key] = filters[key];
			}
		});

		console.log("查询条件:", enhancedFilter);

		// 构建查询
		const query = collection.where(enhancedFilter);
		const countResult = await query.count();
		// 获取销售记录并进行分页
		const result = await query
			.orderBy("isPaid", "asc") // 按照 status 升序排序，0 会排在前面
			.skip((page - 1) * pageSize) // 跳过前面几页的数据
			.limit(pageSize) // 限制每页的数据条数
			.get();

		// 返回结果，包含分页数据
		return {
			code: 0,
			message: "查询成功",
			data: result.data,
			total: countResult.total,
		};
	} catch (error) {
		return {
			code: 1,
			message: "查询失败",
			error,
		};
	}
};

// 新增一条销售记录
exports.addInStockRecord = async (data) => {
	if (!data?.userId) {
		return {
			code: 1,
			message: "新增失败,需要用户！",
		};
	}

	const newData = {
		isDel: 0,
		createTime: new Date(),
		...data,
	};
	try {
		const res = await collection.add(newData);
		return {
			code: 0,
			message: "新增成功",
			data: res,
		};
	} catch (error) {
		return {
			code: 1,
			message: "新增失败",
			error,
		};
	}
};

// 新增多条销售记录
exports.addInStockRecords = async (dataList) => {
	if (!Array.isArray(dataList)) {
		return {
			code: 1,
			message: "新增失败,数据格式错误！",
		};
	} else {
		//开始事务
		const transaction = await db.startTransaction();
		try {
			const promises = dataList.map(async (data) => {
				if (!data?.userId) {
					return {
						code: 1,
						message: "新增失败,需要用户！",
					};
				}
				const newData = {
					isDel: 0,
					createTime: new Date(),
					...data,
				};
				try {
					const res = await transaction.collection("inStock").add(newData);
					return {
						code: 0,
						message: "新增成功",
						data: res,
					};
				} catch (error) {
					return {
						code: 1,
						message: "新增失败",
						error,
					};
				}
			});

			//实现事务
			const res = await Promise.all(promises);
			console.log("res", res);
			if (res.every((item) => item.code === 0)) {
				await transaction.commit();
				return {
					code: 0,
					message: `新增 ${res.length} 条成功`,
				};
			} else {
				await transaction.rollback();
				return {
					code: 1,
					message: "新增失败",
				};
			}
		} catch (e) {
			console.log(e);
			await transaction.rollback();
			return {
				code: 1,
				message: "新增失败",
				error: e,
			};
		}
	}
};

// 根据 ID 获取单条销售记录
exports.getInStockRecordById = async (id) => {
	try {
		// 使用 doc(id).get() 方法根据 ID 获取数据
		const res = await collection.doc(id).get();

		// 如果找到了数据
		if (res.data?.length) {
			return {
				code: 0,
				message: "查询成功",
				data: res.data?.[0],
			};
		} else {
			return {
				code: 1,
				message: "未找到对应的记录",
				data: null,
			};
		}
	} catch (error) {
		return {
			code: 1,
			message: "查询失败",
			error,
		};
	}
};

// 更新入库记录
exports.updateInStockRecord = async (id, data) => {
	const newData = {
		...data,
		updateTime: new Date(),
	};
	try {
		const res = await collection.doc(id).update(newData);
		return {
			code: 0,
			message: "更新成功",
			data: res.updated,
		};
	} catch (error) {
		return {
			code: 1,
			message: "更新失败",
			error,
		};
	}
};
// 删除入库记录
exports.deleteInStockRecord = async (id) => {
	try {
		const res = await collection.doc(id).update({
			isDel: 1,
		});
		return {
			code: 0,
			message: "删除成功",
			data: res.updated,
		};
	} catch (error) {
		return {
			code: 1,
			message: "删除失败",
			error,
		};
	}
};

// 获取 当前厂商 库存 剩余，聚合
exports.getManufacturerGroupList = async (userId) => {
	const res = await collection
		.aggregate()
		.match({
			//未删除
			isDel: 0,
			//剩余库存大于0
			remainingQuantity: dbCmd.gt(0),
			//已入库
			isInStock: true,
			//用户id
			userId,
		})
		.project({
			recordId: "$_id", // 保留原始 _id
			manufacturer: 1,
			specification: 1,
			quantity: 1, // 保留 quantity
			remainingQuantity: 1, // 保留 remainingQuantity
			unitPrice: 1, // 保留 unitPrice
			createTime: 1, // 保留 createTime
			unit: 1, // 保留 unit
		})
		.group({
			_id: {
				manufacturer: "$manufacturer",
				specification: "$specification",
				unit: "$unit",
			},
			ids: {
				$push: "$recordId", // 将 recordId 推送到 ids 数组
			},
			quantitys: {
				$push: "$quantity", // 将 quantity 推送到 quantitys 数组
			},
			remainingQuantitys: {
				$push: "$remainingQuantity", // 将 remainingQuantity 推送到 remainingQuantitys 数组
			},
			unitPrices: {
				$push: "$unitPrice", // 将 unitPrice 推送到 unitPrices 数组
			},
			createTimes: {
				$push: "$createTime", // 将 createTime 推送到 createTimes 数组
			},
			totalQuantity: {
				$sum: "$quantity", // 计算总数量
			},
			totalRemainingQuantity: {
				$sum: "$remainingQuantity", // 剩余总数
			},
		})
		.project({
			_id: 1, // 移除 _id
			manufacturer: "$_id.manufacturer",
			specification: "$_id.specification",
			unit: "$_id.unit",
			totalQuantity: 1,
			totalRemainingQuantity: 1,
			ids: 1,
			quantitys: 1,
			remainingQuantitys: 1,
			unitPrices: 1,
			createTimes: 1,
		})
		.end();
	// 手动将 ids, quantitys, unitPrices,createTimes 合并成一个数组
	const result = res.data.map((item) => {
		const manufacturers = [];
		const len = item.ids.length;
		for (let i = 0; i < len; i++) {
			manufacturers.push({
				id: item.ids[i],
				quantity: item.quantitys[i],
				remainingQuantity: item.remainingQuantitys[i],
				unitPrice: item.unitPrices[i],
				createTime: item.createTimes[i],
			});
		}
		return {
			manufacturer: item.manufacturer,
			specification: item.specification,
			totalQuantity: item.totalQuantity,
			totalRemainingQuantity: item.totalRemainingQuantity,
			manufacturers,
			unit: item.unit,
		};
	});

	return {
		code: 0,
		data: result,
	};
};

// 获取库存统计信息
exports.getStockStatistics = async (userId) => {
	const res = await collection
		.where({
			isDel: 0,
			//剩余库存大于0,
			remainingQuantity: dbCmd.gt(0),
			//已入库
			isInStock: true,
			//用户id
			userId,
		})
		.get();

	//全部
	let totalRemainingQuantity = 0;
	let totalRemainAmount = 0;
	const all = {};

	//已支付
	let totalPaidRemainingQuantity = 0;
	let totalPaidRemainAmount = 0;
	const paid = {};

	//部分支付
	let totalPartPaidRemainingQuantity = 0;
	let totalPartPaidRemainAmount = 0;
	const partPaid = {};

	//未支付
	let totalUnPaidRemainingQuantity = 0;
	let totalUnPaidRemainAmount = 0;
	const unPaid = {};

	//处理对象
	const handleObj = (obj, item) => {
		if (!obj[item.manufacturer + item.specification]) {
			obj[item.manufacturer + item.specification] = {
				manufacturer: item.manufacturer,
				specification: item.specification,
				totalRemainingQuantity: item.remainingQuantity,
				totalRemainAmount: item.remainingQuantity * item.unitPrice,
			};
		} else {
			obj[item.manufacturer + item.specification].totalRemainingQuantity +=
				item.remainingQuantity;
			obj[item.manufacturer + item.specification].totalRemainAmount +=
				item.remainingQuantity * item.unitPrice;
		}
	};

	for (let i = 0; i < res.data.length; i++) {
		//全部
		const item = res.data[i];
		handleObj(all, item);
		totalRemainingQuantity += item.remainingQuantity;
		totalRemainAmount += item.remainingQuantity * item.unitPrice;
		switch (item.status) {
			//未支付
			case 0:
				handleObj(unPaid, item);
				totalUnPaidRemainingQuantity += item.remainingQuantity;
				totalUnPaidRemainAmount += item.remainingQuantity * item.unitPrice;
				break;
				//部分支付
			case 1:
				handleObj(partPaid, item);
				totalPartPaidRemainingQuantity += item.remainingQuantity;
				totalPartPaidRemainAmount += item.remainingQuantity * item.unitPrice;
				break;
				//已支付
			case 2:
				handleObj(paid, item);
				totalPaidRemainingQuantity += item.remainingQuantity;
				totalPaidRemainAmount += item.remainingQuantity * item.unitPrice;
				break;
		}
	}

	return {
		code: 0,
		data: {
			all: {
				totalRemainingQuantity,
				totalRemainAmount,
				list: Object.values(all),
			},
			paid: {
				totalRemainingQuantity: totalPaidRemainingQuantity,
				totalRemainAmount: totalPaidRemainAmount,
				list: Object.values(paid),
			},
			partPaid: {
				totalRemainingQuantity: totalPartPaidRemainingQuantity,
				totalRemainAmount: totalPartPaidRemainAmount,
				list: Object.values(partPaid),
			},
			unPaid: {
				totalRemainingQuantity: totalUnPaidRemainingQuantity,
				totalRemainAmount: totalUnPaidRemainAmount,
				list: Object.values(unPaid),
			},
		},
	};
};

//入库单批量付款
exports.inStockPayment = async ({
	userId,
	paymentAmount
}) => {
	//剩余支付的金额
	let remainingAmount = paymentAmount;

	const transaction = await db.startTransaction();
	//查询还未付清的入库单列表

	try {
		const inStockList = await transaction
			.collection("inStock")
			.where({
				remainingAmount: dbCmd.gt(0), // 剩余金额大于0
				userId, //用户id
			})
			.orderBy("createTime", "asc") // 先进先出
			.get();

		let maxNeedPayAmount = 0;
		for (const inStock of inStockList.data) {
			//剩余金额不够了
			if (remainingAmount <= 0) break;
			maxNeedPayAmount += inStock.remainingAmount;
			//当前付款金额
			const currentPayment = Math.min(remainingAmount, inStock.remainingAmount);
			//剩余金额减去当前扣除金额
			remainingAmount -= currentPayment;
			//更新入库单
			const newData = {
				paidAmount: inStock.paidAmount + currentPayment,
				remainingAmount: inStock.remainingAmount - currentPayment,
				status: inStock.remainingAmount - currentPayment <= 0 ? 2 : 1,
				updateTime: new Date(),
			};
			const res = await transaction
				.collection("inStock")
				.doc(inStock._id)
				.update(newData);
		}

		if (remainingAmount > 0) {
			await transaction.rollback();
			return {
				code: 1,
				message: `付款失败，支付金额超出所有订单需支付金额${maxNeedPayAmount}`,
			};
		} else if (remainingAmount < 0) {
			await transaction.rollback();
			return {
				code: 1,
				message: "付款失败，金额计算错误",
			};
		}

		// 提交事务
		await transaction.commit();
		return {
			code: 0,
			message: "付款成功",
		};
	} catch (error) {
		await transaction.rollback();
		return {
			code: 1,
			message: "付款失败",
			error,
		};
	}
};


// 获取数据库中所有的入库数据，按厂商和规格聚合数量、金额和已付金额（带分页）
exports.getInStockManagerAggregatedData = async (manufacturer, specification, userId, page = 1, pageSize = 10) => {
	try {
		let matchStage = {
			isDel: 0, // 只查询未删除的记录
			userId: userId ,// 按用户 ID 筛选，必须提供
			status: {
				$nin: [2]
			} // 只统计 status 不等于 2（已付清）
		};

		// 如果传入了 manufacturer，则添加筛选条件
		if (manufacturer) {
			matchStage.manufacturer = manufacturer;
		}
		// 如果传入了 specification，则添加筛选条件
		if (specification) {
			matchStage.specification = specification;
		}

		// 计算分页的 skip 值
		const skipCount = (page - 1) * pageSize;

		const result = await collection.aggregate()
			.match(matchStage) // 如果 matchStage 只有 isDel 和 userId，则匹配所有未删除记录
			.group({
				_id: {
					manufacturer: '$manufacturer', // 按厂商分组
					specification: '$specification' // 按规格分组
				},
				totalAmount: {
					$sum: '$totalAmount'
				}, // 总金额，累加所有入库记录的 totalAmount
				totalPaidAmount: {
					$sum: '$paidAmount'
				}, // 总已付金额，累加所有入库记录的 paidAmount
				recordCount: {
					$sum: 1
				}, // 入库记录数量，统计每组的记录总数
				totalQuantity: {
					$sum: '$quantity'
				}, // 总入库数量，累加所有入库记录的 quantity
				lastInStockDate: {
					$max: '$date'
				} // 最近入库日期，取该组所有记录中最晚的 date
			})
			.project({
				manufacturerName: {
					$ifNull: ['$_id.manufacturer', '未知厂商']
				}, // 从 _id 中提取厂商名
				specification: {
					$ifNull: ['$_id.specification', '未知规格']
				}, // 从 _id 中提取规格
				totalAmount: 1, // 总金额
				totalPaidAmount: 1, // 总已付金额
				remainingAmount: { // 剩余金额 = 总金额 - 已付金额
					$subtract: [{
							$ifNull: ['$totalAmount', 0]
						},
						{
							$ifNull: ['$totalPaidAmount', 0]
						}
					]
				},
				recordCount: 1, // 入库记录数量
				totalQuantity: 1, // 总入库数量
				lastInStockDate: 1, // 最近入库日期
				_id: 0 // 移除 _id 字段
			})
			.sort({
				totalAmount: -1
			}) // 按总金额降序排序
			.skip(skipCount) // 跳过前面的记录
			.limit(pageSize) // 限制每页记录数
			.end();

		return {
			success: true,
			data: result?.data || [], // 确保返回空数组而不是 undefined
			message: '入库数据聚合成功'
		};
	} catch (error) {
		return {
			success: false,
			errorMessage: error.message,
			error: error
		};
	}
};